import { Component } from "@angular/core";
import {NavParams, AlertController, LoadingController, ToastController, NavController, Platform} from "ionic-angular";
import {HttpService} from "../../../../providers/http.service";
import {CommonFunc} from "../../../../providers/commonFunc";
import {appConfig } from "../../../../providers/config";
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import {FileOpener} from "@ionic-native/file-opener";
import { File } from '@ionic-native/file';
import {FileChooser} from "@ionic-native/file-chooser";
import {SafeControl} from "../../safe-control/bean/safe-control.bean";
import {HomePage} from "../../../home/home";
import {Storage} from "@ionic/storage";

@Component({
  templateUrl: "safe-control-download.html"
})

//通知详情
export class SafeControlDownload {
  private safeControl: SafeControl = new SafeControl();
  safeControlId : string = "";
  private tempAppConfig = appConfig.IP_URL + appConfig.API.getUpload;

  constructor(
      public navCtrl: NavController,
      private navParams: NavParams,
      private httpService: HttpService,
      private commonFunc: CommonFunc,
      private alertCtrl: AlertController,
      private fileChooser: FileChooser,
      private transfer: FileTransfer,
      private fileOpener: FileOpener,
      private toastCtrl: ToastController,
      private file: File,
      public platform: Platform,
      private storage: Storage,
      private loadingCtrl : LoadingController,
  ) {
    this.safeControl = this.navParams.get("data");
    this.safeControlId = this.navParams.get("safeConId");
    if(this.safeControlId != "" && typeof(this.safeControlId) != "undefined"){
      this.httpService.getSafeConById(this.safeControlId).subscribe(data =>{
        this.safeControl = data.data;
      })
    }
  }

  downloadDoc(index) {
    //查询检查记录。只取第一个文件暂时
    if (index == "1") {
      if (this.safeControl.inspectionRecordsDoc) {
        let fileName = this.safeControl.inspectionRecordsDoc.split(",")[0];
        this.download(fileName);
      } else {
        const toast = this.toastCtrl.create({
          message: '没有检查记录文件',
          duration: 2000,
          position: "top"
        });
        toast.present();
      }
    }

    if (index == "2") {
      if (this.safeControl.lawDocs) {
        let fileName = this.safeControl.lawDocs.split(",")[0];
        this.download(fileName);
      } else {
        const toast = this.toastCtrl.create({
          message: '没有指令书文件',
          duration: 2000,
          position: "top"
        });
        toast.present();
      }
    }
  }

  download(fileName) {
    const url = this.tempAppConfig + fileName;
    if (true) {
      const fileTransfer: FileTransferObject = this.transfer.create();
      let loading = this.loadingCtrl.create({
        content: '下载进度：0%',
        dismissOnPageChange: false
      });
      loading.present();
      let num : number = 0;
      fileTransfer.onProgress(progressEvent =>{
        if(progressEvent.lengthComputable){
          num = progressEvent.loaded / progressEvent.total * 100;
        }
      });

      let timer = setInterval(() =>{
        loading.setContent("下载进度："+Math.floor(num) + "%");
        if(num >= 99){
          clearInterval(timer);
        }
      },10);


      this.file.createDir(this.file.externalRootDirectory, "appFolder", true).then(link => {
        const localPath = this.file.externalRootDirectory + fileName;
        console.log("本地存放路径："+localPath);
        fileTransfer.download(url, localPath).then(entry => {
          if (timer) {
            clearInterval(timer);
          }
          loading.dismiss();
          const nativePath = entry.toURL();
          this.fileOpener.open(nativePath, this.httpService.getFileMimeType(this.httpService.getFileType(fileName))).then(
              () => {
                if (timer) {
                  clearInterval(timer);
                }
                loading.dismiss();
              });
        });
      })


      // let alert = this.alertCtrl.create({
      //   title: '下载进度：0%',
      //   enableBackdropDismiss: false,
      //   buttons: ['后台下载']
      // });
      // alert.present();
      // const fileTransfer: FileTransferObject = this.transfer.create();
      // this.file.createDir(this.file.externalRootDirectory, "appFolder", true).then(link => {
      //   const localPath = this.file.externalRootDirectory + fileName;
      //   console.log("本地存放路径："+localPath);
      //   fileTransfer.download(url, localPath).then((entry) => {
      //     const nativePath = entry.toURL();
      //     this.fileOpener.open(nativePath, this.httpService.getFileMimeType(this.httpService.getFileType(fileName))).then(
      //         () => {
      //         });
      //   });
      // })
      //
      // let num : number = 1;
      // fileTransfer.onProgress((event: ProgressEvent) => {
      //   num = Math.floor(event.loaded / event.total * 100);
      //   if (num === 100) {
      //     alert.dismiss();
      //   } else {
      //     let title = document.getElementsByClassName('alert-title')[0];
      //     title && (title.innerHTML = '下载进度：' + num + '%');
      //   }
      // });
    }
  }

  backHome(){
    //this.navCtrl.push(HomePage,{});
      this.navCtrl.setRoot(HomePage);
  }

}